﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;
using System.Windows.Media.Animation;

namespace PmuRegistry.Silverlight.Pages.Manage
{
	public partial class VendorDevices : Page
	{
		PhasorDataServiceClient m_client;
		bool m_inEditMode = false;
		int m_vendorDeviceID = 0;

		public VendorDevices()
		{
			InitializeComponent();
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetVendorDeviceListCompleted += new EventHandler<GetVendorDeviceListCompletedEventArgs>(client_GetVendorDeviceListCompleted);
			m_client.GetVendorsCompleted += new EventHandler<GetVendorsCompletedEventArgs>(client_GetVendorsCompleted);
			m_client.SaveVendorDeviceCompleted += new EventHandler<SaveVendorDeviceCompletedEventArgs>(client_SaveVendorDeviceCompleted);
			Loaded += new RoutedEventHandler(VendorDevices_Loaded);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			ListBoxVendorDeviceList.SelectionChanged += new SelectionChangedEventHandler(ListBoxVendorDeviceList_SelectionChanged);			
		}
				
		void client_SaveVendorDeviceCompleted(object sender, SaveVendorDeviceCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Vendor Device Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			m_client.GetVendorDeviceListAsync(); //Refresh data to reflect changes on the current screen.
		}
		
        void ListBoxVendorDeviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ListBoxVendorDeviceList.SelectedIndex >= 0)
			{
				VendorDevice selectedVendorDevice = ListBoxVendorDeviceList.SelectedItem as VendorDevice;
				GridVendorDeviceDetail.DataContext = selectedVendorDevice;
				ComboBoxVendor.SelectedItem = new KeyValuePair<int, string>(selectedVendorDevice.VendorID, selectedVendorDevice.VendorName);
				m_vendorDeviceID = selectedVendorDevice.ID;
				m_inEditMode = true;
			}
		}
		
        void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();

			ClearForm();
		}

        void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            Storyboard sb = new Storyboard();
            sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
            sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
            Storyboard.SetTarget(sb, ButtonSaveTransform);
            sb.Begin();

            if (IsValid())
            {
                VendorDevice vendorDevice = new VendorDevice();
                KeyValuePair<int, string> selectedVendor = (KeyValuePair<int, string>)ComboBoxVendor.SelectedItem;
                vendorDevice.VendorID = selectedVendor.Key;
                vendorDevice.Name = TextBoxName.Text.CleanText();
                vendorDevice.Description = TextBoxDescription.Text.CleanText();
                vendorDevice.URL = TextBoxUrl.Text.CleanText();

                if (m_vendorDeviceID != 0 && m_inEditMode == true)
                {
                    vendorDevice.ID = m_vendorDeviceID;
                    m_client.SaveVendorDeviceAsync(vendorDevice, false);
                }
                else
                    m_client.SaveVendorDeviceAsync(vendorDevice, true);
            }
        }

        bool IsValid()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(TextBoxName.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Name", SystemMessage = "Please provide valid Name.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxName.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            return isValid;
        }
		
        void VendorDevices_Loaded(object sender, RoutedEventArgs e)
		{			
		}
		
        void client_GetVendorsCompleted(object sender, GetVendorsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboBoxVendor.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Vendors", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboBoxVendor.Items.Count > 0)
				ComboBoxVendor.SelectedIndex = 0;
		}
		
        void client_GetVendorDeviceListCompleted(object sender, GetVendorDeviceListCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxVendorDeviceList.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Vendor Device List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}
		
        void ClearForm()
		{
			if (ComboBoxVendor.Items.Count > 0)
				ComboBoxVendor.SelectedIndex = 0;
			GridVendorDeviceDetail.DataContext = new VendorDevice();	//Bind an empty element.	
			m_inEditMode = false;
			m_vendorDeviceID = 0;
			ListBoxVendorDeviceList.SelectedIndex = -1;
		}

		// Executes when the user navigates to this page. Event happens before loaded.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			m_client.GetVendorsAsync(false);
			m_client.GetVendorDeviceListAsync();
		}

	}
}
